package com.jackrain.nea.common;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ReferenceUtil;
import com.jackrain.nea.web.QueryCmd;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;

/**
 * @author wuwenxue
 * @date 2018/07/04
 **/
@Service
public class QueryCpUtil {

    @Reference(group = "cp",version = "2")
    private QueryCmd queryCmd;

    /**
     * 跨库查询
     *
     * @param tableName 表名
     * @param field     字段
     * @param whereJson 条件
     * @return hashmap
     */
    public JSONObject queryCP(String tableName, String field, JSONObject whereJson) {
        HashMap cpHashMap = new HashMap(16);
        cpHashMap.put("type", HashMap.class);
        cpHashMap.put("tableName", tableName);
        cpHashMap.put("fields", field);
        cpHashMap.put("whereKeys", whereJson);

        Object o = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(),
                "com.jackrain.nea.web.QueryCmd",
                "cp", "2");
        HashMap result = (HashMap) ((QueryCmd) o).queryTable(cpHashMap);

        JSONObject cpJson = new JSONObject(result);

        return cpJson;
    }

    /**
     * 跨库查询
     *
     * @param tableName 表名
     * @param field     字段
     * @param whereJson 条件
     * @return JSONArray
     */
    public JSONArray queryCPJsonArray(String tableName, String field, JSONObject whereJson) {
        HashMap cpHashMap = new HashMap(16);
        cpHashMap.put("type", List.class);
        cpHashMap.put("tableName", tableName);
        cpHashMap.put("fields", field);
        cpHashMap.put("whereKeys", whereJson);

        Object o = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(),
                "com.jackrain.nea.web.QueryCmd",
                "cp", "2");
        List<HashMap> listData = (List<HashMap>) ((QueryCmd) o).queryTable(cpHashMap);
        JSONArray cpArray = new JSONArray();

        for (HashMap hashMap : listData) {
            JSONObject cpJson = new JSONObject(hashMap);
            cpArray.add(cpJson);
        }
        return cpArray;
    }


}
